$(function () {
  var editor; //源代码editor对象
  createCodeMirror(); //创建源代码editor对象
  createRootMenu();// 生成左侧菜单
  registerEvent(); //注册页面事件
  if (!location.hash) {
    //如果没有输入案列，设置默认案例
    location.hash = "live-ppt";
  } else {
    refreshCodeMirror();
  }
  setActiveMenu();//设置选中菜单样式
  //创建源代码editor对象
  function createCodeMirror() {
    var mixedMode = {
      name: "htmlmixed",
      scriptTypes: [
        {
          matches: /\/x-handlebars-template|\/x-mustache/i,
          mode: null,
        },
        {
          matches: /(text|application)\/(x-)?vb(a|script)/i,
          mode: "vbscript",
        },
      ],
    };
    //源码编辑对象
    editor = CodeMirror.fromTextArea(document.getElementById("code-area"), {
      mode: mixedMode,
      selectionPointer: true,
      lineNumbers: false,
      matchBrackets: true,
      indentUnit: 4,
      indentWithTabs: true,
    });
    autodivheight(); //设置源码区域高度
  }
  // 获取源码文件
  function setEditorValue(fileName) {
    $.get(fileName, function (data) {
      editor.setValue(data);
    });
  }
  // 刷新源代码
  function refreshCodeMirror() {
    var caseId = this.location.hash.substr(1);
    $('.frame-area').html('');
    if (caseInList(caseId)) {
      var fileName = "./demo/";
      var dir = caseId.split('-')[0]
      fileName += dir +'/'+ caseId + ".html"
      setEditorValue(fileName);
      createFrom()
    } else {
      alert("案例不存在");
    }
  }
  // 判断示例是否在示例库中
  function caseInList(caseId) {
    var flag = false;
    for (var i = 0; i < caseList.length; i++) {
      if (caseList[i].id == caseId) {
        flag = true;
        break;
      }
    }
    return flag;
  }

  // 点击运行处理函数
  function submitTryit() {
    var text = editor.getValue();
    var $frame = $('<iframe></iframe>')
    $frame.attr("frameborder","0")
    $frame.attr("scrolling","yes")
    $frame.attr("id","iframeResult")
    $frame.attr("width","100%")
    $frame.attr("height","98%")
    $("#frameContainer").html('')
    $("#frameContainer").append($frame)
    $("#frameContainer").removeClass('frame-area-empty')
    var frameDom = $frame[0].contentDocument? $frame[0].contentDocument:$frame[0].document
    frameDom.open()
    frameDom.write(text)
    frameDom.close()
  }

  //检查参数是否输入
  function checkParams() {
    var flag = true;
    $(".exe-form input").each(function (i, el) {
      if ($.trim($(el).val()).length == 0) {
        flag = false;
        $(el).focus();
        return false;
      }
    });
    return flag;
  }
  //设置editor的高度
  function autodivheight() {
    var height = $("#pre-area-left").height();
    editor.setSize("100%", height);
  }
  //生成表单参数字符串
  function createParamStr() {
    var str = "";
    $(".exe-form input").each(function (i, el) {
      str += "var " + el.id + '="' + $.trim($(el).val()) + '";';
    });
    return str;
  }
  // 注册页面
  function registerEvent() {
    // hashchange事件
    window.addEventListener(
      "hashchange",
      function (e) {
        refreshCodeMirror();
      },
      false
    );
    // 页面尺寸改变时
    window.addEventListener("resize", autodivheight);
    // 【点击运行】按钮
    $(".exe-form").on('click','#tryexe',function () {
      if (!checkParams()) {
        $(".tips").show();
        return;
      }
      $(".tips").hide();
      var newStr = createParamStr(); // 从表单中获取参数
      repalceCaseParams(newStr); //替换源码中的空参数
      submitTryit();
    });
    //注册菜单点击事件
    $(".menu-list").on('click', '.menu-lvl2',function () {
      location.hash = $(this).attr("data-hash");
      $("#frameContainer").addClass('frame-area-empty')
      setActiveMenu()
    });
    $(".menu-list").on('click', '.menu-lvl1',function () {
      $(this).next().toggleClass('menu-expand')
      var $iEl = $(this).find('i').eq(0)
      if($iEl.hasClass('icon-add')){
        $iEl.removeClass('icon-add')
        $iEl.addClass('icon-reduce')
      }else{
        $iEl.removeClass('icon-reduce')
        $iEl.addClass('icon-add')
      }
      setLevel2MenuHeight($(this).next())
    });
    // 刷新
    $(".icon-refresh").click(function(){
      refreshCodeMirror()
    })
    // 下载
    $('.icon-download').click(function(){
      var aEle = document.createElement('a')
      var caseId = window.location.hash.substr(1)
      aEle.download = caseId
      var fileName = "./demo/";
      var dir = caseId.split('-')[0]
      fileName += dir +'/'+ caseId + ".html"
      aEle.href = fileName
      aEle.click()
    })
  }
  //生成替换字符串
  function repalceCaseParams(newStr) {
    var tmpStr = editor.getValue();
    var startIndex = tmpStr.indexOf("//参数开始") + 6;
    var endIndex = tmpStr.indexOf("//参数结束");
    var str = tmpStr.substring(startIndex, endIndex);
    var finalStr = tmpStr.replace(str, "\n" + newStr + "\n");
    editor.setValue(finalStr);
  }
  // 生成左侧菜单
  function createRootMenu() {
    var html = ''
    for (var i = 0, len = rootMenu.length; i < len; i++) {
      html += '<h2 class="menu-lvl1"><i class="icon-menu1 iconfont icon-add"></i>'+rootMenu[i].text+'</h2>'
      var subMenuStr = createSubMenu(rootMenu[i].id)
      html += subMenuStr
    }
    $('.menu-list').html(html)
  }
  function createSubMenu(parentId) {
    var html = '<ul class="menu-lvl2-wraper">'
    for (var i = 0, len = caseList.length; i < len; i++) {
      if(parentId==caseList[i].parentId){
        html +=  '<li class="menu-lvl2" data-index="'+i+'" data-hash="'+caseList[i].id+'">'+caseList[i].text+'</li>'
      }
    }
    html += '</ul>'
    return html;
  }
  // 设置菜单选中效果
  function setActiveMenu(){
    $('.menu-lvl2').removeClass('menu-active')
    // $('.menu-lvl2').parent().removeClass('menu-expand')
    $('.menu-lvl2').each(function(){
      var caseId =window.location.hash.substr(1);
      var menuData = $(this).attr('data-hash')
      if(caseId == menuData){
        $(this).addClass('menu-active')
        $(this).parent().addClass('menu-expand')
        var $iEl = $(this).parent().prev().find('i').eq(0)
        $iEl.removeClass('icon-add')
        $iEl.addClass('icon-reduce')
        setLevel2MenuHeight($(this).parent())
      }
    })
  }
  function setLevel2MenuHeight($menu){
    var perHeight = $menu.find('li').eq(0).height()
    if($menu.hasClass('menu-expand')){
      $menu.height($menu.find('li').length*perHeight)
    }else{
      $menu.height(0)
    }
  }
});
